import DPlayer from 'dplayer'
import flvjs from '../../../../assets/flvjs/flv1.6.2.js'
// import flvjs from '../../../../../../../../../../flv.js(1.6.2)/dist/flv'
// import flvjs from '../../../../assets/flvjs/flv20170321.min'

export default {
  methods: {
    // 初始化视频
    flvjsInitDPlayer(container, url) {
      this.canplay = false
      let flvPlayer
      if (!container || !url) return
      let player = new DPlayer({
        container,
        video: {
          url,
          type: 'customFlv',
          customType: {
            customFlv: function (video, player) {
              flvPlayer = flvjs.createPlayer(
                {
                  cors: true,
                  type: 'flv',
                  isLive: this.isLive,
                  isRecording: !this.isLive,
                  // isLive: true,
                  hasAudio: Boolean(this.hasAudio),
                  hasVideo: Boolean(!this.hasAudio),
                  // hasAudio:true,
                  // hasVideo:true,
                  url,
                  withCredentials: false,
                  segments: [
                    {
                      cors: true,
                      timestampBase: 0,
                      withCredentials: false,
                      url,
                    },
                  ],
                },
                {
                  // enableWorker: false,
                  // lazyLoadMaxDuration: 3 * 60,
                  // seekType: "range",

                  // enableWorker: true,
                  // // 懒加载
                  lazyLoad: true,
                  lazyLoadMaxDuration: 30000 * 60,

                  seekType: 'range',
                  // // 缓存
                  // // enableStashBuffer: this.realTime === "smooth",
                  // // stashInitialSize: this.realTime === "smooth" ? 128 : 0,
                  enableStashBuffer: false,
                  stashInitialSize: 2046,

                  autoFastForward: true,
                }
              )
              flvPlayer.attachMediaElement(video)
              flvPlayer.load()
            },
          },
        },
        volume: 0,
        live: this.isLive,
        // live: true,
        autoplay: true,
        screenshot: true,
        mutex: false,
        hotkey: false,
      })
      player.flvPlayer = flvPlayer
      player.video.playbackRate = this.times?.value || 1
      this.$nextTick(() => {
        this.isPlay = !player.video.paused
        this.updateDisplayScale()
      })
      player.on('play', () => {
        this.$emit('play', this.id)
        this.isPlay = true
      })
      player.on('destroy', () => {
        this.$emit('destroy', this.id)
        this.speed = 0
        this.isPlay = false
      })
      flvPlayer.on('statistics_info', (res) => {
        // console.log('statistics_info',res);
        this.speed = res.speed.toFixed(1)
      })
      // 监听video播放器播放时间的变化
      if (this.isLive) {
        player.on('timeupdate', function () {
          // console.log("正在播放------");
          // console.log(player.video);

          // 计算表最新推流的时间和现在播放器播放推流的时间
          if (
            !player.video.currentTime ||
            !player.video.buffered.end(0) ||
            player.video.currentTime < 0 ||
            !player.video.buffered.end(0) < 0
          )
            return
          let differTime =
            player.video.buffered.end(0) - player.video.currentTime
          // console.log(differTime);

          // 差值小于1.5s时根据1倍速进行播放
          if (differTime < 1) {
            player.video.playbackRate = 1
          }

          // 差值大于1.5s小于10s根据1.2倍速进行播放
          if (differTime < 10 && differTime > 1) {
            player.video.playbackRate = 2
            // console.log(player.video.duration)
          }

          //console.log(videoFlvPlayer.buffered);
          // 差值大于10s时进行重新加载直播流
          if (differTime > 10) {
            // console.log("重新刷新流!!");
            // console.log(player.video.buffered.end(0),player.video.currentTime,differTime)

            if (player.video.buffered.end(0) > 10000) {
              player.play()
              return
            }
            player.video.playbackRate = 1
            player.video.currentTime = Math.floor(player.video.buffered.end(0))
            // 注意这里重新加载video是自己封装的方法，需要销毁video并重新创建video
            // $scope.videoPlay({liveUrl: videoFlvOptions.sources[0].src})
          }
        })
      } else {
        player.on('timeupdate', (a, b, c) => {
          // console.log(player.video.buffered.end(0), player.video.currentTime);
          // let differTime =
          //   player.video.buffered.end(0) - player.video.currentTime;

          // if (differTime < 0)
          //   player.video.currentTime = Math.floor(player.video.buffered.end(0));
          this.axisNum = player.video.currentTime
          this.$emit('timeupdate', this.axisNum)
          if (player.video.buffered.length > 0)
            this.assistantNum = player.video.buffered.end(0)
          // this.assistantNum = player.video.buffered.end(0);
        })
      }
      player.on('durationchange', (a, b, c) => {
        this.duration = this.progOption.max = player.video.duration
      })
      this.flvjsEventText(player)
      return player
    },
    // 事件测试
    flvjsEventText(player) {
      // 视频事件
      let videoEventList = [
        { name: 'abort', text: '当发生中止事件时运行脚本' },
        { name: 'canplay', text: '在有足够的数据可以播放时触发' },
        // {name: 'canplaythrough', text: '当媒介能够无需因缓冲而停止即可播放至结尾时运行脚本'},
        // {name: 'durationchange', text: '当媒介长度改变时运行脚本'},
        // {name: 'emptied', text: '当媒介资源元素突然为空时（网络错误、加载错误等）运行脚本'},
        { name: 'ended', text: '结束时触发' },
        { name: 'error', text: '发生错误时触发' },
        // {name: 'loadeddata', text: '当加载媒介数据时运行脚本'},
        // {name: 'loadedmetadata', text: '当媒介元素的持续时间以及其他媒介数据已加载时运行脚本'},
        // {name: 'loadstart', text: '当浏览器开始加载媒介数据时运行脚本'},
        { name: 'mozaudioavailable', text: '' },
        { name: 'pause', text: '暂停时触发' }, // 暂停时触发
        // {name: 'play', text: '开始播放时触发'},
        // {name: 'playing', text: '播放时定期触发'},
        // {name: 'progress', text: '当浏览器正在取媒介数据时运行脚本'},
        // {name: 'ratechange', text: '当媒介数据的播放速率改变时运行脚本'},
        // {name: 'seeked', text: '当媒介元素的定位属性 [1] 不再为真且定位已结束时运行脚本'},
        // {name: 'seeking', text: '当媒介元素的定位属性为真且定位已开始时运行脚本'},
        {
          name: 'stalled',
          text: '当取回媒介数据过程中（延迟）存在错误时运行脚本',
        },
        {
          name: 'suspend',
          text: '当浏览器已在取媒介数据但在取回整个媒介文件之前停止时运行脚本',
        },
        // {name: 'timeupdate', text: '当媒介改变其播放位置时运行脚本'},
        // {name: 'volumechange', text: '当媒介改变音量亦或当音量被设置为静音时运行脚本'},
        // {name: 'waiting', text: '当媒介已停止播放但打算继续播放时运行脚本'}
      ]

      videoEventList.forEach((item) => {
        player.on(item.name, (a, b, c) => {
          // console.log('视频事件' + item.name + ':' + item.text)
          // console.log(a,b,c);
          if (item.name == 'error') {
            // console.log('flvjs报错')
            if (this.$refs.video && this.realIsPlay) this.flvjsRelink()
          }
          if (item.name == 'ended') {
            // console.log('flvjs结束')
            if (this.isLive && this.$refs.video && this.realIsPlay)
              this.flvjsRelink()
          }
          if (item.name == 'canplay') this.canplay = true
        })
      })
    },
    // 重新连接
    flvjsRelink() {
      // console.log(connectTimeoutFlag);
      let connectTimeoutFlag
      if (connectTimeoutFlag) {
        clearTimeout(connectTimeoutFlag)
        connectTimeoutFlag = null
        return
      }
      this.destroy()
      connectTimeoutFlag = setTimeout(() => {
        console.log('回连-------------' + this.infoText)
        if (!this.isPlay && !this.player) {
          this.playVideo()
        } else {
          clearTimeout(connectTimeoutFlag)
          connectTimeoutFlag = null
        }
      }, 5000)
    },
    // 切换播放状态播放
    flvjsPlayVideo(isPlay) {
      if (typeof isPlay === 'boolean') {
        this.realIsPlay = isPlay
        if (!isPlay) {
          this.destroy()
        } else {
          this.player = this.initDPlayer(this.$refs.video, this.url)
        }
        return
      }
      if (this.isPlay) {
        this.destroy()
      } else {
        this.player = this.initDPlayer(this.$refs.video, this.url)
      }
    },
    // 销毁
    flvjsDestroy() {
      if (!this.player?.flvPlayer) return
      this.player.flvPlayer.unload()
      this.player.flvPlayer.detachMediaElement()
      this.player.flvPlayer.destroy()
      this.player.flvPlayer = null
      this.player.destroy()
      this.assistantNum = 0
      this.duration = 0
      this.player = null
    },
    // 切换显示比例 speed 4:3 16:9 filling
    flvjsUpdateDisplayScale() {
      let scale = this.displayScale
      let videoEl = this.$refs.video.getElementsByClassName('dplayer-video')[0]
      let elWidth = this.$refs.video.clientWidth
      let elHeight = this.$refs.video.clientHeight
      let ratio = elWidth / elHeight
      switch (scale) {
        case '4:3':
          if (ratio > 4 / 3) {
            videoEl.style.height = '100%'
            videoEl.style.width = elHeight * (4 / 3) + 'px'
          } else {
            videoEl.style.height = elWidth * (3 / 4) + 'px'
            videoEl.style.width = '100%'
          }
          break
        case '16:9':
          if (ratio > 16 / 9) {
            videoEl.style.height = '100%'
            videoEl.style.width = elHeight * (16 / 9) + 'px'
          } else {
            videoEl.style.height = elWidth * (9 / 16) + 'px'
            videoEl.style.width = '100%'
          }
          break
        default:
          videoEl.style.height = ''
          videoEl.style.width = ''
      }
    },
  },
}
// </script>
